<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\UsersModel;
use App\Model\WithdrawalModel;
use App\Services\SmsServices;
use App\Services\WechatServices;
use Illuminate\Support\Facades\DB;

class UsersDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = UsersModel::query();

        $query->when(checkIsHasField($params,'phone'),function ($query)use ($params){
            $query->where('phone',$params['phone']);
        });

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'spread_id'),function ($query)use ($params){
            $query->where('spread_id',$params['spread_id']);
        });
        $query->when(checkIsHasField($params,'shop_nums'),function ($query)use ($params){
            $query->where('shop_nums',$params['shop_nums']);
        });

        return $query->orderByDesc('created_at');
    }


    /**
     * @throws SysExceptions
     */
    public static function login($params = []): array
    {
        checkForData(['code','code2'],['请授权','请授权'],$params);
//        SmsServices::checkVerCode($params['ver_code'],$params['phone']);
        $result = WechatServices::wechat_login($params['code'],'','',$params['code2']);
        $users = self::builder_query(['phone'=>$result['phone']]);
        if(!$users->exists()){
            $inserData = [
                'phone'=>$result['phone'],
                'openid'=>$result['openid'],
                'nickname'=>'排队免单用户',
                'password'=>'',
                'head_img'=>'https://skyre.oss-cn-hangzhou.aliyuncs.com/20240517063354-1715927634.jpg',
            ];
            if(checkIsHasField($params,'spread_id')){
                $inserData['spread_id'] = $params['spread_id'];
            }

            if(checkIsHasField($params,'buess_id')){
                $inserData['buess_id'] = $params['buess_id'];
            }

            if(self::builder_query()->create($inserData) === false){
                self::error('登录失败2');
            }
        }
        $users->update([
            'openid'=>$result['openid']
        ]);
        $info =  $users->first()->toArray();
        return  $info;
    }

    public static function getUserInfo(array $array): array
    {
        $info =  self::builder_query($array)->first()->toArray();
        $info['address'] = AddressDao::address_info(['user_id'=>$info['user_id']]);
        $info['all_price'] = LineUpPriceDao::builder_query([
            'user_id'=>$array['user_id']
        ])->sum('now_price');
        return $info;
    }

    public static function users(array $all): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $lists =  self::builder_query($all)->paginate();
        foreach ($lists as $user) {
            $user->extra_city_str = '暂无区域'; // 添加字段
            if($user['shop_level'] != 0){
                $data = explode(',',$user['city_str']);
                $city_str = implode(',',AreaDao::builder_query()->whereIn('area_id',$data)->pluck('name')->toArray());
                $user->extra_city_str = $city_str;
            }
        }
        return $lists;
    }

    //用户充值
    public static function recharge(array $params)
    {
        if ($params['money'] < 0){
         //查询用户
            $userInfo = UsersDao::getUserInfo([
                'user_id'=>$params['user_id']
            ]);
            if($userInfo['money'] < -($params['money'])){
                self::error('用户余额不足~');
            }
        }
        try {
            BillsDao::moneysUpdate($params['money'],$params['user_id'],'系统充值');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    /**
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function setPayPass(array $params)
    {
        checkForData(['pay_pass','ver_code'],['请输入支付密码','请输入验证码'],$params);
        $userInfo = UsersDao::getUserInfo(['user_id'=>$params['user_id']]);
        SmsServices::checkVerCode($params['ver_code'],$userInfo['phone']);
        $params['pay_pass'] = password_hash($params['pay_pass'],PASSWORD_DEFAULT);
        if(self::builder_query(['user_id'=>$params['user_id']])->update(['pay_pass'=>$params['pay_pass']]) === false){
            self::error('设置失败');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function check_pass($pay_pass, $user_id)
    {
        $user_mysql_pass = self::builder_query(['user_id'=>$user_id])->value('pay_pass');
        if(is_null($user_mysql_pass) || empty($user_mysql_pass)){
            self::error('请设置支付密码!');
        }
        if(!password_verify($pay_pass,$user_mysql_pass)){
            self::error('密码不正确');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function setUserData(array $params)
    {
        checkForData(['nickname','head_img'],['请输入用户昵称','请上传用户头像'],$params);
        if(self::builder_query(['user_id'=>$params['user_id']])->update(self::filterFields($params,new UsersModel())) === false){
            self::error('上传失败');
        }
    }

    /**
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function moneysToUsers(array $params)
    {
            checkForData(['nums','phone','pay_pass'],['请输入数量','请输入手机号','请输入密码'],$params);
            self::check_pass($params['pay_pass'],$params['user_id']);
            //获取对方用户
            $userQuery = self::builder_query(['phone'=>$params['phone']]);
            if(!$userQuery->exists()){
                self::error('用户不存在');
            }
            $ToUerInfo = $userQuery->first()->toArray();
            //获取当前用户信息
            $NowUserInfo = self::getUserInfo(['user_id'=>$params['user_id']]);
            if($NowUserInfo['money'] < $params['nums']){
                self::error('用户金额不正确');
            }
            DB::beginTransaction();
            try {
                BillsDao::moneysUpdate(-($params['nums']),$NowUserInfo['user_id'],'用户转账支出');
                BillsDao::moneysUpdate($params['nums'],$ToUerInfo['user_id'],'用户转账收入');
                DB::commit();
            }catch (\Exception $exception){
                DB::rollBack();
                self::error($exception->getMessage());
            }
    }

    /**
     * @desc 获取小区业绩
     * @param int $int
     * @return int
     */
    public static function minPrices(int $user_id = 0): int
    {
        //获取我的下级
        $my_upper_query = self::builder_query([
            'spread_id'=>$user_id
        ]);
        if(!$my_upper_query->exists()){
            return 0;
        }
        $my_upper = $my_upper_query->get()->toArray();
        if(count($my_upper) == 1){
            return 0;
        }
        $prics_tuan = $my_upper_query->pluck('pv_nums_tuan')->toArray();

        //获得下级的个人业绩
        $price_ziji = $my_upper_query->pluck('pv_nums_ziji')->toArray();

        return array_sum($prics_tuan)-max($prics_tuan)+array_sum($price_ziji);
    }

    public static function updateHeadNIckname($wechatInfo,$user_id)
    {
        self::builder_query(['user_id'=>$user_id])->update([
            'nickname'=>$wechatInfo['nickname'],
            'head_img'=>$wechatInfo['headimgurl'],
        ]);
    }

    /**
     * @desc 设置
     * @param array|null $params
     * @return void
     */
    public static function setShopLevel(array $params)
    {
        DB::beginTransaction();
        $adminQuery = AdminDao::getAdminBuilderQuery([
            'username'=>$params['shop_nums']
        ]);
        if($adminQuery->exists()){
            self::error('账号已存在');
        }
        try {
            //创建账号
            $adminQuery->create([
                'username'=>$params['shop_nums'],
                'password'=>password_hash($params['password'],PASSWORD_DEFAULT),
                'name'=>$params['name'],
                'menu_ids'=>'84,85,86,88,89,93,92'
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());

        }
    }



    public static function setCardJson(array $params)
    {
        checkForData(['name','card_no','card_kai'],['请输入姓名','请输入卡号','请输入开户行'],$params);
        if(self::builder_query(['user_id'=>self::deleteParamId($params,'user_id')])->update(['card_json_data'=>json_encode($params)]) === false){
            self::error('设置失败');
        }
    }

    public static function withdrawal(array $params)
    {
        checkForData(['nums'],['请输入数量'],$params);
        $userInfo = self::builder_query(['user_id'=>$params['user_id']])->first()->toArray();
        if($userInfo['card_json_data'] == NULL){
            self::error('请绑定银行卡');
        }
        if($userInfo['money'] < $params['nums']){
            self::error('余额不足');
        }
        DB::beginTransaction();
        $dataFee = $params['nums']*0.1;
        try {
            BillsDao::moneysUpdate(-($params['nums']),$params['user_id'],'用户提现');
//            BillsDao::moneysUpdate(-($params['nums']-$dataFee),$params['user_id'],'用户提现手续费');

            WithdrawalModel::query()->create([
                'card_json_data'=>$userInfo['card_json_data'],
                'user_id'=>$params['user_id'],
                'fee'=>$dataFee,
                'nums'=>$params['nums']-$dataFee,
                'status'=>0
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function register(array $params)
    {
        checkForData(['phone','spread_id','password','re_password'],['请输入手机号','清扫描推荐码','请输入密码','请输入密码'],$params);
        if($params['password'] != $params['re_password']){
            self::error('两次密码不一致');
        }
        if(!checkIsHasField($params,'spread_id')){
            self::error('没有推荐人');
        }
        if(self::builder_query([
            'phone'=>$params['phone']
        ])->exists()){
            self::error('手机号已存在');
        }
        $inserData = [
            'phone'=>$params['phone'],
            'nickname'=>'排队免单用户',
            'password'=>password_hash($params['password'],PASSWORD_DEFAULT),
            'head_img'=>'https://skyre.oss-cn-hangzhou.aliyuncs.com/20240517063354-1715927634.jpg',
        ];
        $inserData['spread_id'] = $params['spread_id'];
        if(self::builder_query()->create($inserData) === false){
            self::error('登录失败');
        }

    }

    /**
     * @throws SysExceptions
     */
    public static function set_login_pass(array $params)
    {
        checkForData(['password','ver_code'],['请输入密码','请输入验证码'],$params);
        $userInfo = UsersDao::getUserInfo(['user_id'=>$params['user_id']]);
        SmsServices::checkVerCode($params['ver_code'],$userInfo['phone']);
        $params['password'] = password_hash($params['password'],PASSWORD_DEFAULT);
        if(self::builder_query(['user_id'=>$params['user_id']])->update(['password'=>$params['password']]) === false){
            self::error('设置失败');
        }
    }

    public static function changePrices($price,$user_id)
    {
        UsersDao::builder_query(['user_id'=>$user_id])->increment('prices',$price);
    }
}
